import {ref} from "vue";
import {onAddToFavorites, onLoad, onShareAppMessage, onShareTimeline, onShow} from "@dcloudio/uni-app";
import {
    buyGoldAPI,
    discountConfigListAPI,
    failDiscountAPI,
    getConfigAPI,
    getMtUrlAPI,
    getUserInfoAPI,
    goldRechargeListAPI,
    receiveDiscountAPI,
    recodeLogAPI,
    relaxAPI,
    saveMtUrlAPI
} from "../services/me";
import {useUserInfoStore} from "../stores/modules/userInfo";
import {usePayHook} from "../hooks/usePay";
import {useCommonInfoStore} from "../stores/modules/commonInfo";

export const useCountTimeStore = () => {

    // 美团连接
    const mtLink = ref("")
    const fkLink = ref()
    const showMessage = ref("")
    const messageTitle = ref("")
    const btnText = ref("")

    const timeCount = ref(10)
    const time = ref()
    const isStart = ref(false)
    const setTimeStart = (timeCountVal) => {
        if (time.value && isStart.value === true) {
            return
        }
        timeCount.value = timeCountVal ? timeCountVal : 10
        time.value = setInterval(() => {
            timeCount.value--
            isStart.value = true
            console.log("timeCount", timeCount.value + "")
            if (time.value && timeCount.value === 0) {
                isStart.value = false
                timeCount.value = timeCountVal ? timeCountVal : 10
                clearInterval(time.value)
            }
        }, 1000)
    }

    const toWeb = () => {
        // #ifdef APP-PLUS
        plus.runtime.openURL("https://i.meituan.com/mttouch/page/account")
        // #endif
        // #ifdef H5
        window.location.href = "https://i.meituan.com/mttouch/page/account"
        // #endif
        close()
    }

    // 保存和修改连接
    const saveMTLink = async () => {
        if (!mtLink.value) {
            await uni.showToast({title: "请先获取美团账号链接", icon: 'none', duration: 2000})
            return
        }
        const res = await saveMtUrlAPI(mtLink.value)
        await uni.showToast({title: res.msg, icon: 'none', duration: 2000})
    }

    const queryResult = async (result_url) => {
        let count = 60
        return new Promise(async (resolve, reject) => {
            await uni.showLoading({title: "优惠券发放中"})
            let isRequest = false // 是否正在请求
            let timerI = setInterval(async () => {
                if (!isRequest) {
                    isRequest = true
                    uni.request({
                        url: result_url, //仅为示例，并非真实接口地址。
                        method: 'GET',
                        success: async (res) => {
                            isRequest = false
                            const resQuery = res.data
                            if (resQuery?.data?.recordStatus !== 0) {
                                clearTimeout(timerI)
                                uni.hideLoading()
                                await recodeLogAPI({data: res, "type": 1})
                                resolve(resQuery?.data?.recordStatus)
                            } else {
                                if (count === 0) {
                                    clearTimeout(timerI)
                                    uni.hideLoading()
                                    await recodeLogAPI({data: res, "type": 0})
                                    resolve(19)
                                }
                                count = count - 1
                            }

                        },
                        async fail(err) {
                            isRequest = false
                            clearTimeout(timerI)
                            resolve(29)
                            await recodeLogAPI({data: err, "type": 2})
                            uni.hideLoading()
                        },
                    });
                }
            }, 3000)
        })
    }

    // 领取红包
    const toGetRedBag = async () => {
        if (!currentDiscountConfig?.value?.coupon_type) {
            await uni.showToast({title: "请选择优惠券套餐", icon: 'none', duration: 2000})
            return
        }
        close()
        let type = 0
        if (urlCountData.value.user_count <= 0) {
            // uni.showToast({title: "", icon: 'none', duration: 2000})
            type = 14
            showTips(type)
            return
        }
        if (!mtLink.value) {
            await uni.showToast({title: "请先获取美团账号链接", icon: 'none', duration: 2000})
            return
        }
        if (!isStart.value) {
            if (config.value?.my_gold_coin > 200 || isVIP) {
                type = 0
                setTimeStart(10)
            } else {
                type = 15
                showTips(type)
                return
            }
        } else {
            await uni.showToast({title: "请求频繁，请稍后再试", icon: 'none', duration: 2000})
            return
        }
        const res = await receiveDiscountAPI(mtLink.value, currentDiscountConfig.value.coupon_type, currentDiscountConfig.value.title)
        console.log("res===", res)
        if (!res.result.result_url) {
            return
        }
        type = await queryResult(res.result.result_url, res.result.discount_redeem_id)
        console.log("type===", type)
        if (type !== 3) {
            console.log("领取失败===", res)
            // Type不等于3领取失败，调用失败上报
            await failDiscountAPI(res.result.discount_redeem_id)
        } else {
            console.log("领取成功===")
            // 领取成功，调用刷新配置列表
            await getDiscountConfigListAPI()
        }
        showTips(type)
    }

    /**
     * 根据类型显示提示信息
     * @param {number} type - 提示类型，不同的类型对应不同的提示内容和逻辑处理
     */
    const showTips = (type) => {
        // 根据不同的类型显示不同的提示信息和按钮文本
        switch (type) {
            case 3:
                urlCountData.value.user_count = urlCountData.value.user_count - 1
                if (!isVIP.value) {
                    config.value.my_gold_coin = config.value.my_gold_coin - 200
                }
                messageTitle.value = "领取成功"
                showMessage.value = "优惠券到账成功，可到美团账号查看，报名霸王餐，点外卖更省；低至1元吃外卖"
                btnText.value = "去报名"
                break;
            case 2:
                messageTitle.value = "领取失败"
                showMessage.value = "抱歉，红包领取失败-不扣账号金币，账号可能存在风控，是否去解除风控？"
                btnText.value = "解除风控"
                break
            case 1:
            case 4:
            case 5:
            case 7:
            case 19:
            case 29:
                messageTitle.value = "领取失败"
                showMessage.value = "抱歉，红包领取失败-不扣账号金币"
                btnText.value = "去报名"
                break;
            case 6:
            case 8:
                messageTitle.value = "领取失败"
                showMessage.value = "抱歉，红包领取失败-不扣账号金币地址失败或错误，请点击重新获取最新账号地址后重新填写地址领取"
                btnText.value = "确定"
                break;
            case 14:
                messageTitle.value = "领取提示"
                showMessage.value = "抱歉，今日领取次数不足，请次日再试"
                btnText.value = "去报名"
                break;
            case 15:
                messageTitle.value = "领取失败"
                showMessage.value = "您的金币不足"
                btnText.value = "去充值"
                break;
        }
        // 显示模态框，根据类型执行相应的操作
        uni.showModal({
            title: messageTitle.value + " - " + type,
            content: showMessage.value,
            confirmText: btnText.value,
            success: async function (res) {
                if (res.confirm) {
                    if (res.confirm) {
                        switch (type) {
                            case 1:
                            case 3:
                            case 4:
                            case 5:
                            case 7:
                            case 14:
                                await uni.switchTab({url: "/pages/index/index"})
                                break;
                            case 15:
                                show.value = true;
                                break;
                            case 2:
                                showFK.value = true
                                break;
                        }
                    }
                }
            }
        });
    }

    // 取金币信息
    const config = ref()
    // 获取金币信息
    const getTaskInfo = async () => {
        const configRes = await getConfigAPI()
        config.value = configRes.result
    }
    const toFuLi = () => {
        uni.switchTab({url: "/pages/fuli/fuli"})
    }
    const toMakeMoney = () => {
        uni.switchTab({url: "/pages/makemoney/makemoney"})
    }
    onLoad(async () => {
        await getTaskInfo()
    })

    // 显示金币充值
    const show = ref(false)
    const showGetTip = ref(false)
    // 关闭金币充值
    const close = () => {
        show.value = false
        showGetTip.value = false
        isShowTC.value = false
        showFK.value = false
        showFKTip.value = false
    }
    // 小程序点击账号连接提示
    const showTip = () => {
        // #ifdef H5 || APP-PLUS
        showGetTip.value = true
        // #endif
        // #ifdef MP-WEIXIN
        uni.showModal({
            title: "温馨提示",
            content: "请到公众号或APP获取美团账号连接",
            confirmText: "打开教程",
            success: async function (res) {
                if (res.confirm) {
                    await uni.navigateTo({
                        url: '/pages/index/toweburl?url=' + "https://mp.weixin.qq.com/s/3DGtfJ_OF4ix9cKtSk6x5g"
                    })
                    // uni.setClipboardData({
                    //     data: "https://i.meituan.com/mttouch/page/account",
                    //     success() {
                    //         //https://mp.weixin.qq.com/s?__biz=Mzg2NTgzOTEyNg==&mid=2247485041&idx=1&sn=585b04001b8dd16a8cdf4a04ddfad257&chksm=ce52b708f9253e1e02e95f2f92967a8072d6824ae04910bd6b2a9f36a5191668312bf9e1fac0#rd
                    //         uni.showToast({
                    //             title: '复制地址成功',
                    //             icon: 'none',
                    //         })
                    //     },
                    // })
                }
            }
        });
        // #endif
    }
    // 金币List
    const listGold = ref([])
    const currentItem = ref()
    // 点击金币列表
    const clickItem = (item) => {
        listGold.value.forEach((itemC) => {
            itemC.isSelect = false
        })
        item.isSelect = true
        currentItem.value = item
    }
    // 点击跳转公众号
    const toJCOne = () => {
        uni.showToast("123123")
        // #ifdef MP
        uni.navigateTo({
            url: '/pages/index/toweburl?url=' + urlCountData.value.url1
        })
        // #endif
        // #ifdef APP-PLUS
        uni.navigateTo({
            url: '/pages/index/toweburl?url=' + urlCountData.value.url1
        })
        // #endif
        // #ifdef H5
        window.location.href = urlCountData.value.url1
        // #endif
    }
    // 点击跳转公众号
    const toJCTow = () => {
        // #ifdef MP
        uni.navigateTo({
            url: '/pages/index/toweburl?url=' + urlCountData.value.url2
        })
        // #endif
        // #ifdef APP-PLUS
        uni.navigateTo({
            url: '/pages/index/toweburl?url=' + urlCountData.value.url2
        })
        // #endif
        // #ifdef H5
        window.location.href = urlCountData.value.url2
        // #endif
    }
    const toJCThree = () => {
        // #ifdef MP
        uni.navigateTo({
            url: '/pages/index/toweburl?url=' + urlCountData.value.url3
        })
        // #endif
        // #ifdef APP-PLUS
        uni.navigateTo({
            url: '/pages/index/toweburl?url=' + urlCountData.value.url3
        })
        // #endif
        // #ifdef H5
        window.location.href = urlCountData.value.url3
        // #endif
    }
    const userInfoStore = useUserInfoStore()
    // 显示支付
    const showPay = ref(false)
    // 当前支付类型
    const NewPayType = ref('applet_wechat')
    // 支付方式选择
    const NewradioChange = (evt) => {
        NewPayType.value = evt.currentTarget.dataset.type
    }
    // 购买金币
    const buyGold = async () => {
        const res = await buyGoldAPI(NewPayType.value, currentItem.value.gold_type)
        if (NewPayType.value === "balance") {
            showPay.value = false
            await userInfoStore.getUserInfo()
            await getTaskInfo()
            return
        }
        const payInfo = res.result
        uni.hideLoading()
        console.log('payInfo--->', payInfo)
        if (NewPayType.value === "app_alipay") {
            await usePayHook().aliPay(payInfo.pay_string, '充值金币', () => {
                showPay.value = false
                userInfoStore.getUserInfo()
                getTaskInfo()
            })
            return
        }
        await usePayHook().wxPay(payInfo, '充值金币', () => {
            showPay.value = false
            userInfoStore.getUserInfo()
            getTaskInfo()
        })
    }
    // 支付类型
    const payTypeList = ref([
        {
            name: '微信支付',
            // #ifdef H5
            type: 'wechat',
            // #endif
            // #ifdef APP-PLUS
            type: 'app_wechat',
            // #endif
            // #ifdef MP-WEIXIN
            type: 'applet_wechat'
            // #endif
        },
        // #ifdef APP-PLUS
        // {
        //     name: '支付宝支付',
        //     // #ifdef APP-PLUS
        //     type: 'app_alipay',
        //     // #endif
        // },
        // #endif
    ])

    const buyGoldClick = () => {
        showPay.value = true
    }

    const isShowTC = ref(false)
    const showFK = ref(false)
    const showFKTip = ref(false)
    const showTC = () => {
        if (currentDiscountConfig.value?.isSelect) {
            currentDiscountConfig.value.isSelect = false
        }
        currentDiscountConfig.value = {}
        isShowTC.value = true
    }

    const discountConfigList = ref([])
    const currentDiscountConfig = ref()
    // 获取神卷套餐数据
    const getDiscountConfigListAPI = async () => {
        const res = await discountConfigListAPI()
        discountConfigList.value = res.result
        // if (discountConfigList.value.length > 0) {
        //     clickDiscountConfigItem(discountConfigList.value[0])
        // }
    }

    const clickDiscountConfigItem = (item) => {
        if (item.status !== 0) {
            uni.showToast({title: "选择的套餐不可领取", icon: 'none', duration: 2000})
            return
        }
        discountConfigList.value.forEach((itemC) => {
            itemC.isSelect = false
        })
        item.isSelect = true
        currentDiscountConfig.value = item
    }


    /**
     * 风控接口调用
     * 此函数首先检查变量fkLink.value是否为空如果为空，则显示提示信息要求用户输入连接
     * 如果fkLink.value不为空，则调用风控接口函数，并关闭当前窗口，然后显示提示信息
     */
    const openErr = async () => {
        // 检查fkLink.value是否为空，如果为空，则显示提示信息
        if (!fkLink.value) {
            await uni.showToast({title: "请输入连接", icon: 'none', duration: 2000})
            return
        }
        // 调用API获取折扣配置信息
        await relaxAPI(fkLink.value)
        // 关闭当前窗口
        close()
        // 显示提示信息
        showFKTip.value = true
    }

    const isVIP = ref(false)
    const urlCountData = ref()
    onLoad(async () => {
        // #ifdef H5
        NewPayType.value = 'wechat'
        // #endif
        // #ifdef APP-PLUS
        NewPayType.value = 'app_wechat'
        // #endif
        // #ifdef MP-WEIXIN
        NewPayType.value = 'applet_wechat'
        // #endif
        const resultRes = await goldRechargeListAPI()
        listGold.value = resultRes.result
        if (listGold.value.length > 0) {
            clickItem(listGold.value[0])
        }
        const urlRes = await getMtUrlAPI()
        urlCountData.value = urlRes.result
        mtLink.value = urlCountData.value.discount_url
        await getDiscountConfigListAPI()
        isVIP.value = userInfoStore.userInfo?.is_member === 1
    })

    onShow(async () => {
        if (userInfoStore.isLogin('您还未登录，是否去登录？', 1)) {
            // 登录后获取用户信息
            await getUserInfo()
        }
    })


    // onLoad(async (options)=>{
    //     if (options?.parent_id) {
    //         commonInfoStore.setParentUid(options.parent_id)
    //     }
    //     if (options?.scene) {
    //         const scene = decodeURIComponent(options.scene)
    //         commonInfoStore.setParentUid(scene)
    //     }
    //     if (useUser.isLoginBool()) {
    //         if (commonInfoStore.parentId && !useUser.userInfo.parent_id) {
    //             await getBindPidAPI(commonInfoStore.parentId)
    //         }
    //     }
    // })


    const getUserInfo = async () => {
        const res = await getUserInfoAPI()
        userInfoStore.setUserInfo(res.result)
        // 是否绑定手机号
        if (!userInfoStore.userInfo.username) {
            uni.showModal({
                title: '绑定手机号-提示',
                content: '您还未绑定手机号，手机号用于抢单、订单核验，和订单状态通知，是否去绑定？',
                confirmText: '去绑定',
                success: async function (res) {
                    if (res.confirm) {
                        await uni.navigateTo({
                            url: "/pagesme/settinginfo"
                        })
                    }
                }
            })
        }
    }

    const commonInfoStore = useCommonInfoStore() // 使用commonInfoStore状态管理器
    const message = ref("点外卖用领食周边购，每餐只要0-5元")

    // 初始化分享数据
    onShow(() => {
        commonInfoStore.setWxShareMessage("message", message.value, userInfoStore.userInfo.id, "/pages_gold/mt_redbag?parent_id=" + userInfoStore.userInfo.id);
    })

    // 转发到聊天界面
    onShareAppMessage(() => {
        return commonInfoStore.setWxShareMessage("message", message.value, userInfoStore.userInfo.id, "/pages_gold/mt_redbag?parent_id=" + userInfoStore.userInfo.id);
    })

    // 转发到朋友圈
    onShareTimeline(() => {
        return commonInfoStore.setWxShareMessage("friend", message.value, userInfoStore.userInfo.id, "/pages_gold/mt_redbag?parent_id=" + userInfoStore.userInfo.id);
    })

    // 添加到收藏
    onAddToFavorites(() => {
        return commonInfoStore.setWxShareMessage("favorite", message.value, userInfoStore.userInfo.id, "/pages_gold/mt_redbag?parent_id=" + userInfoStore.userInfo.id);
    })

    return {
        isVIP,
        show,
        showPay,
        NewPayType,
        payTypeList,
        listGold,
        config,
        urlCountData,
        btnText,
        mtLink,
        isStart,
        timeCount,
        showMessage,
        messageTitle,
        showGetTip,
        discountConfigList,
        isShowTC,
        showFK,
        showFKTip,
        buyGold,
        clickItem,
        close,
        showTip,
        toJCOne,
        toJCTow,
        NewradioChange,
        setTimeStart,
        saveMTLink,
        toGetRedBag,
        getTaskInfo,
        toFuLi,
        toWeb,
        toMakeMoney,
        buyGoldClick,
        clickDiscountConfigItem,
        showTC,
        toJCThree,
        openErr,
        fkLink
    }
}